/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yangxu.hospital.system.modules.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yangxu.hospital.common.utils.FileUtil;
import com.yangxu.hospital.common.utils.PageResult;
import com.yangxu.hospital.common.utils.PageUtil;
import com.yangxu.hospital.common.utils.SecurityUtils;
import com.yangxu.hospital.system.modules.system.domain.Appointment;
import com.yangxu.hospital.system.modules.system.domain.User;
import com.yangxu.hospital.system.modules.system.domain.dto.AppointmentDto;
import com.yangxu.hospital.system.modules.system.service.UserService;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangxu.hospital.system.modules.system.service.AppointmentService;
import com.yangxu.hospital.system.modules.system.domain.vo.AppointmentQueryCriteria;
import com.yangxu.hospital.system.modules.system.mapper.AppointmentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @description 服务实现
* @author 杨旭
* @date 2024-11-25
**/
@Service
@RequiredArgsConstructor
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements AppointmentService {

    private final AppointmentMapper appointmentMapper;
    private final UserService userService;

    @Override
    public PageResult<AppointmentDto> queryAll(AppointmentQueryCriteria criteria, Page<Object> page){
        Long currentUserId = SecurityUtils.getCurrentUserId();
        // 如果是管理员，返回全部
        if (currentUserId != 1L){
            criteria.setDoctorId(currentUserId);
        }
//        // 如果是医生，返回自己的预约
//        // 查出所有用户
//        List<User> users = userService.list();
//        // 将用户列表转换为 Map 以便快速查找
//        Map<Long, String> userMap = users.stream()
//                .filter(Objects::nonNull) // 确保用户对象不为 null
//                .filter(user -> user.getId() != null && user.getNickName() != null) // 确保 id 和 nickName 都不为 null
//                .collect(Collectors.toMap(
//                        User::getId,
//                        User::getNickName,
//                        (existing, replacement) -> existing, // 如果有重复的 key，保留现有的值
//                        HashMap::new // 提供一个 HashMap 构造器，以避免在并发环境下的潜在问题
//                ));
//        // 查出所有科室
//
//        // 查出所有预约
        IPage<AppointmentDto> all = appointmentMapper.findAll(criteria, page);
//
//        List<AppointmentDto> records = all.getRecords();
//        // 设置预约用户名字和医生名字
//        records.forEach(appointmentDto -> {
//            Long patientId = appointmentDto.getPatientId();
//            // 设置用户名字
//            appointmentDto.setPatientName(userMap.get(patientId)); // 设置用户名字
//
//            Long doctorId = appointmentDto.getDoctorId();
//            appointmentDto.setDoctorName(userMap.get(doctorId)); // 设置医生名字
//        });

        return PageUtil.toPage(all);
    }

    @Override
    public List<Appointment> queryAll(AppointmentQueryCriteria criteria){
        return appointmentMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Appointment resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Appointment resources) {
        Appointment appointment = getById(resources.getAppointmentId());
        appointment.copy(resources);
        saveOrUpdate(appointment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Appointment> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Appointment appointment : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("患者ID", appointment.getPatientId());
            map.put("医生ID", appointment.getDoctorId());
            map.put("预约时间", appointment.getAppointmentTime());
            map.put("预约状态", appointment.getStatus());
            map.put("创建时间", appointment.getCreateTime());
            map.put("更新时间", appointment.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<AppointmentDto> getList(Long currentUserId) {
        return appointmentMapper.getList(currentUserId);
    }

    @Override
    public AppointmentDto findById(Long id) {
        return appointmentMapper.findById(id);
    }
}